package cn.ming.leo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.PagedList;

import cn.ming.leo.bean.DoorTools;
import cn.ming.leo.bean.User;
import cn.ming.leo.bean.vo.RedisProductBean;
import cn.ming.leo.utils.Message;
import cn.ming.leo.utils.PageListModel;

@Service
public class DoorToolsService {

	@Autowired
	RedisService redisService;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public Message<String> productDoors(String topic, RedisProductBean redisProductBean) {
		stringRedisTemplate.convertAndSend(topic, JSON.toJSONString(redisProductBean));
		return new Message<String>("ok");
	}

	public Message<DoorTools> getById(int id) {
		return new Message<DoorTools>(DoorTools.find.byId("" + id));
	}

	public Message<PageListModel<DoorTools>> findAll(Integer toosIds, Integer pageIndex, Integer pageSize) {
		PagedList<DoorTools> pl;
		ExpressionList<DoorTools> pression = Ebean.find(DoorTools.class).where();

		pageIndex = (pageIndex == null) ? 0 : pageIndex - 1;
		pageSize = (pageSize == null) ? 10 : pageSize;

		if (toosIds != null) {
			pression = pression.eq("tools_id", toosIds);
		}

		pl = pression.order().desc("create_time").findPagedList(pageIndex, pageSize);

		PageListModel<DoorTools> pageListModel = new PageListModel<DoorTools>(pl);

		for (DoorTools doorTools : pageListModel.getList()) {
			doorTools.setPutUserName(User.find.byId("" + doorTools.getPutUserId()).getMobile());

			if (doorTools.getTakeUserId() != 0) {
				doorTools.setTakeUserName(User.find.byId("" + doorTools.getTakeUserId()).getMobile());
			}

		}
		return new Message<PageListModel<DoorTools>>(pageListModel);
	}

	public Message<PageListModel<DoorTools>> reparis(Integer pageIndex, Integer pageSize) {
		PagedList<DoorTools> pl;
		ExpressionList<DoorTools> pression = Ebean.find(DoorTools.class).where();

		pageIndex = (pageIndex == null) ? 0 : pageIndex - 1;
		pageSize = (pageSize == null) ? 10 : pageSize;

		String[] statuss = { "3", "5" };
		pl = pression.in("status", statuss).order().desc("create_time").findPagedList(pageIndex, pageSize);

		PageListModel<DoorTools> pageListModel = new PageListModel<DoorTools>(pl);

		for (DoorTools doorTools : pageListModel.getList()) {
			doorTools.setPutUserName(User.find.byId("" + doorTools.getPutUserId()).getMobile());

			if (doorTools.getTakeUserId() != 0) {
				doorTools.setTakeUserName(User.find.byId("" + doorTools.getTakeUserId()).getMobile());
			}

		}
		return new Message<PageListModel<DoorTools>>(pageListModel);
	}

}
